<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'

const router = useRouter()
const mixedList = ref([])
const loading = ref(true)
const error = ref(false)

// 可靠的洗牌算法
const shuffleArray = (array) => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]]
  }
  return array
}

// 数据获取
const fetchData = async () => {
  try {
    loading.value = true
    error.value = false

    const [videosRes, picsRes] = await Promise.all([
      axios.get('http://localhost:8080/api/videos', {
        params: { _: Date.now() } // 防止缓存
      }),
      axios.get('http://localhost:8080/api/pic-cases', {
        params: { _: Date.now() }
      })
    ])

    const videosData = videosRes.data.map(v => ({
      ...v,
      type: 'video',
      isShowImg: true
    }))

    const picsData = picsRes.data.map(p => ({
      ...p,
      type: 'pic'
    }))

    mixedList.value = shuffleArray([...videosData, ...picsData])
  } catch (err) {
    console.error('数据加载失败:', err)
    error.value = true
    Toast.fail('数据加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 视频控制
const toggleVideo = (item) => {
  item.isShowImg = !item.isShowImg
  const videoEl = document.getElementById(`video-${item.id}`)

  if (videoEl) {
    if (item.isShowImg) {
      videoEl.pause()
      videoEl.currentTime = 0
    } else {
      videoEl.play().catch(() => {
        Toast('点击屏幕开始播放')
      })
    }
  }
}

const onClickLeft = () => {
  router.push('/declare')
}

// 初始化
onMounted(async () => {
  window.scrollTo(0, 0)
  await fetchData()
})
</script>

<template>
  <div>
    <van-nav-bar title="案例处理" left-text="返回" left-arrow @click-left="onClickLeft" fixed safe-area-inset-top
      style="z-index: 999;" />
    <div style="height: 46px;"></div>

    <!-- 加载状态 -->
    <van-loading v-if="loading" vertical size="24px" class="loading-container">
      加载中...
    </van-loading>

    <!-- 错误提示 -->
    <van-empty v-else-if="error" description="数据加载失败" class="error-container">
      <van-button round type="primary" @click="fetchData">
        重新加载
      </van-button>
    </van-empty>

    <!-- 内容区域 -->
    <template v-else>
      <div v-for="item in mixedList" :key="`${item.type}-${item.id}`" class="case-item">
        <!-- 视频类型 -->
        <template v-if="item.type === 'video'">
          <div v-if="item.isShowImg" class="image-container" @click="toggleVideo(item)">
            <img :src="item.pic_url || 'https://picsum.photos/200/200'" class="media" alt="视频封面">
            <svg class="play-button" width="50" height="50" viewBox="0 0 24 24" fill="none"
              xmlns="http://www.w3.org/2000/svg">
              <circle cx="12" cy="12" r="10" stroke="#fff" stroke-width="2" />
              <polygon points="12,8 16,12 12,16" fill="#fff" />
            </svg>
          </div>
          <video v-else :id="`video-${item.id}`" class="media" controls playsinline @ended="() => toggleVideo(item)">
            <source :src="item.video_url" type="video/mp4">
            您的浏览器不支持 video 标签
          </video>
          <van-cell-group>
            <van-cell :title="item.title" :label="`${item.play_count}次播放`" />
          </van-cell-group>
        </template>

        <!-- 图片类型 -->
        <template v-else-if="item.type === 'pic'">
          <img :src="item.pic_url" class="media" alt="案例图片" loading="lazy">
          <van-cell-group>
            <van-cell :title="item.title" :label="`${item.play_count}次浏览`" />
          </van-cell-group>
        </template>
      </div>
    </template>
  </div>
</template>

<style scoped>
.case-item {
  margin-bottom: 20px;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.image-container {
  position: relative;
  width: 100%;
  height: 200px;
  cursor: pointer;
  background: #f5f5f5;
}

.media {
  width: 100%;
  height: 200px;
  object-fit: cover;
  background: linear-gradient(45deg, #f5f5f5, #e0e0e0);
}

.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  cursor: pointer;
  transition: transform 0.2s;
}

.play-button:hover {
  transform: translate(-50%, -50%) scale(1.1);
}

.van-cell-group {
  margin: 0;
  padding: 12px 16px;
}

.van-cell {
  padding: 8px 0;
}

.loading-container {
  padding-top: 100px;
  text-align: center;
}

.error-container {
  padding-top: 80px;
}
</style>